package ws

import (
	socketio "github.com/googollee/go-socket.io"
	"iot-base/auth/api/logic"
	"iot-base/auth/common/socket"
	"iot-base/auth/config"
	Log "iot-base/auth/logger"
	"iot-base/auth/svc"
	"iot-base/auth/types"
	"iot-base/auth/utils"
	"iot-base/common/jwt"
	"net/url"
	"strconv"
)

// OnConnect 建立链接.
func OnConnect(s socketio.Conn) error {
	var uid int64
	values, _ := url.ParseQuery(s.URL().RawQuery)
	if values != nil {
		token := values.Get("token")
		if token != "" {
			j := jwt.NewJWT()
			claims, err := j.ParseToken(token)
			if err != nil {
				Log.Log.Errorf("OnConnect token err")
				s.Close()
				return err
			}
			uid, _ = strconv.ParseInt(claims.ID, 10, 64)
			socket.Manager.Register <- socket.IoClient{
				Conn: s,
				Uid:  uid,
			}
		}
	}
	isAdmin, _ := logic.NewUserLogic().IsSysAdmin(uid)
	if isAdmin {
		//fmt.Println("管理员加入房间", uid)
		socket.IoRoom.AddRoom(strconv.FormatInt(config.SystemAdmin, 10), uid)
	} else {
		//fmt.Println("普通用户加入房间", uid)
		// 查询用户拥有用的组
		groupModel := svc.Dao.TAuthGroup
		groups, err := groupModel.GetUserGroup(uid)
		if err != nil {
			Log.Log.Errorf("OnConnect groupModel.GetUserGroup err=%v", err)
			s.Close()
			return err
		}
		// 加入房间
		for _, v := range groups {
			socket.IoRoom.AddRoom(strconv.FormatInt(v.ID, 10), uid)
		}
	}
	total, err := logic.NewAlarmLogic().ActiveAlarmNum(uid)
	if err != nil {
		Log.Log.Errorf("logic.NewAlarmLogic().ActiveAlarmNum err:=%v", err)
	}
	//fmt.Println("推送消息:", total)
	s.Emit(config.EventAlarm, types.NewSocketIoResult().Success(utils.H{"alarm_total": total, "info": utils.H{}}, ""))
	return nil
}

func OnDisconnect(s socketio.Conn, reason string) {
	// 退出订阅
	conn, err := socket.StoreSocketIo.Get(s.ID())
	if err == nil {
		socket.Sub.UnSubAll(conn.Uid)
	}
	// 注销
	socket.Manager.Unregister <- s.ID()
}
